Date.prototype.format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,                 //月份
    "d+": this.getDate(),                    //日
    "h+": this.getHours(),                   //小时
    "m+": this.getMinutes(),                 //分
    "s+": this.getSeconds(),                 //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds()             //毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
}

function getDeviceId(node_id, device_slave_id, iSModbus) {
  let deviceId = node_id;
  if (iSModbus) {
    deviceId = device_slave_id.split(".")[0];
  }
  return deviceId
}

/**
 * 重新设置图表初始化
 * @param chart
 * @param option
 * @returns
 */
function setChartOption(chart, option) {
  chart.setOption(option, true);
  cfg.current_edit_obj.children(".chartStyle").attr("option", JSON.stringify(option));
}

/**
 * 获取echarts对象
 * @returns
 */
function getEchartObj() {
  var current_edit_obj = cfg.current_edit_obj;
  var chart = app.chartMap[current_edit_obj.attr("id")];
  if (chart == null) {
    var $chartHtml = current_edit_obj.children(".chartStyle");
    $chartHtml.html("");
    chart = echarts.init($chartHtml[0]);
    app.chartMap[current_edit_obj.attr("id")] = chart;
  }
  return chart;
}

/**
 * 初始化模板地图
 */
function initTemplateMap(id) {
  var map = new BMap.Map(id);
  map.enableScrollWheelZoom(true);
  map.centerAndZoom(new BMap.Point(118.7812, 32.0712), 13);
  app.bdMap[id] = map;
}

/**
 * 绑定点击或者时间事件
 */
function initTextOrTime() {
  $("div[nid='0']").each(function () {
    if ($(this).attr("cid") == 6) {
      ;
    } else {
      if (isNotEmpty($(this).attr("jty")) && isNotEmpty($(this).attr("jurl"))) {
        $(this).click(function () {
          if ($(this).attr("jty") == 1) {
            let width = $(this).attr("width");
            let height = $(this).attr("height");
            // 弹窗
            layer.open({
              type: 2,
              title: ' 设备详情',
              shadeClose: true,
              shade: 0,
              //maxmin: true, //开启最大化最小化按钮
              area: [width !== '' ? width + 'px' : '80%', height !== '' ? height + 'px' : '80%'],
              content: $(this).attr("jurl")
            });
          } else {
            window.location.href = $(this).attr("jurl");
          }
        })
      }
    }
  })
  setInterval(function () {
    $("div[nid='0']").each(function () {
      if ($(this).attr("cid") == 6) {
        // 时间控件，则需要定期更新时间
        $(this).find("span").text(timeStamp2String(new Date()));
      }
    })
  }, 1000);
}

/**
 * 初始化设备状态
 */
function initDeviceStatus() {
  // eslint-disable-next-line no-undef
  $(".deviceStateNode").each(function () {
    var id = $(this).attr("id");
    var node_id = $(this).attr("node_id");
    var that = this;
    if (node_id != null) {
      getAjax(iotbaseurl + 'api/v1/dev/isOnline?devCode=' + node_id, function (res) {
        if (res) {
          var cmd = gdv(eval('(' + $(that).attr('cmd') + ')'), []);
          var cmdValue = 18;
          if (res.Data.IsOnline == true) {
            cmdValue = 16
          }
          for (var i = 0; i < cmd.length; i++) {
            if (cmdValue >= cmd[i].min && ((cmd[i].min == cmd[i].max && cmdValue == cmd[i].max) || cmdValue < cmd[i].max)) {
              $(that).find("img").attr("src", cmd[i].src);
              $(that).attr("val", cmdValue);
              break;
            }
          }
        }
      });
    }
  })
}

/**
 * 地图初始化
 * @returns
 */
function initMap() {
  $(".mapNode").each(function () {
    var id = $(this).attr("id");
    var node_id = $(this).attr("node_id");
    initTemplateMap(id);
    if (node_id != null) {
      var map = app.bdMap[id];
      getAjax(baseurl + 'api/device/' + node_id, function (e) {
        if (e) {
          var data = e;
          var lonLat = data.point.split(',')
          var str_name = 'location2.png';
          if (data.iot_node_status != 16) {
            str_name = 'location2_red.png';
          }
          var myIcon = new BMap.Icon("../../bigscreen/image/" + str_name, new BMap.Size(30, 37));
          var point = new BMap.Point(lonLat[0], lonLat[1]);
          var marker = new BMap.Marker(point, {icon: myIcon});  // 创建标注
          map.addOverlay(marker);
          map.centerAndZoom(point, 6);              // 将标注添加到地图中
        }
      });
    }
  })
}

/**
 * 修改多值开关
 */
function multivaluedSwitch(name, value) {
  let objs = $("div[nid=9][sensor_id=" + name + "]");
  for (var k = 0; k < objs.length; k++) {
    var obj = objs.eq(k);
    var cmdValue = parseInt(value);
    var cmd = gdv(eval('(' + obj.attr('cmd') + ')'), []);
    for (var i = 0; i < cmd.length; i++) {
      let pmin = parseInt(cmd[i].min);
      let pmax = parseInt(cmd[i].max);
      if (cmdValue >= pmin && ((pmin == pmax && cmdValue == pmax) || cmdValue < pmax)) {
        obj.attr("val", cmdValue);
        obj.find("img").attr("src", cmd[i].src);
        break;
      }
    }
  }
}

function switchLinkUpdate(name, value) {
  let objs = $("div[nid=14][sensor_id=" + name + "]");
  for (var k = 0; k < objs.length; k++) {
    var obj = objs.eq(k);
    var cmdValue = value;
    if (!isNaN(Number(cmdValue))) {
      cmdValue = parseInt(value);
    }
    var cmd = gdv(eval('(' + obj.attr('cmd') + ')'), []);
    for (var i = 0; i < cmd.length; i++) {
      if (cmd[i].is_num != false) {
        let pmin = parseInt(cmd[i].min);
        let pmax = parseInt(cmd[i].max);
        if (cmdValue >= pmin && ((pmin == pmax && cmdValue == pmax) || cmdValue < pmax)) {
          obj.attr("jval", cmdValue);
          obj.find("a").attr("href", cmd[i].jurl);
          break;
        }
      } else {
        if (cmdValue == cmd[i].val) {
          obj.attr("jval", cmdValue);
          obj.find("a").attr("href", cmd[i].jurl);
          break;
        }
      }

    }
  }
}

function checkNid(values, dataValue, key, deviceId, dateTime) {
  let obj = $(values);
  let nid = $(values).attr("nid");
  let cid = $(values).attr("cid");
  let cmd = '';
  let cmdValue = '';
  switch (nid) {
    case "1":// 数值数据、配置数据、状态数据展示\数据时间
      let value = "";
      if (cid === "7") {
        value = (dataValue != null && dataValue !== '' ? dataValue : '00:00')

        if (value.length < 4) {
          value = value.padStart(4, '0');
          value = value.toString().slice(0, 2) + ':' + value.toString().slice(2);
        }
        obj.attr("val", value);
        obj.find(".canvas_text").html(value)
      } else if (cid === "11" || cid === "12") {
        value = (dataValue != null && dataValue !== '' ? dataValue : 0.00)
        obj.attr("val", value);
        obj.find(".canvas_text").html(value)
      } else if (cid === "13") {
        obj.find("span").html(timeStamp2String(dateTime))
      }
      break;
    case "5":
      let id = $(values).attr("id");
      if (cid === '3') {
        app.chartMap[id].setOption({
          series: [{
            data: [{value: dataValue, name: obj.attr('DisplayName')}]
          }]
        });
      } else if (cid === '4') {
        let max = $(values).attr('max');
        app.chartMap[id].setOption({
          series: [{
            data: [{name: 'sensor', value: (values != null && values !== '' ? parseInt(values) : 0) / max}]
          }]
        });
      }/*else if (cid === '10'){
				let json = $(values).find('div').attr("option");
				let option = JSON.parse(json);
				option.series[0].effect.show = dataValue > 0;
				app.chartMap[id].setOption(option);
			}*/ else {
        let unit = $(values).attr('unit');
        let sensor_id = $(values).attr('sensor_id');
        commonAjax("POST", iotbaseurl + 'api/v1/curve/list', {
          'DevCode': deviceId,
          'FieldName': sensor_id
        }, function (res) {
          if (res.Data.length > 0) {
            var x_data = [];
            var y_data = [];
            let echartsData = [];
            if (res) {
              var datat = res.Data;
              if (datat != null) {
                let sortS = [];
                for (let w in datat) {
                  let elem = [datat[w].DataTime, datat[w].Value];
                  sortS.push(elem);
                }
                echartsData.push({
                  name: key,
                  connectNulls: false,
                  data: sortS
                });
              }
            }
            app.chartMap[id].x_data = x_data;
            app.chartMap[id].y_data = y_data;
            app.chartMap[id].setOption({
              grid: {
                left: '3%',
                right: '4%',
                bottom: '4%',
                containLabel: true
              },
              dataZoom: [
                {
                  show: true,
                  start: 90,
                  end: 100
                },
                {
                  type: 'inside',
                  start: 0,
                  end: 100,
                  handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                  handleSize: '80%',
                  handleStyle: {
                    color: '#fff',
                    shadowBlur: 3,
                    shadowColor: 'rgba(0, 0, 0, 0.6)',
                    shadowOffsetX: 2,
                    shadowOffsetY: 2
                  }
                }
              ],
              tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                  let result = '';
                  params.forEach(function (item) {
                    let date = new Date(item.value[0])
                    result += date.format("MM-dd hh:mm:ss") + "</br>" + item.marker + " " + item.seriesName + ":" + item.value[1] + "</br>";
                    //result+=formattedDate+ "</br>" + item.marker + " " + item.seriesName + ":" + item.value[1] + "</br>";
                  });
                  return result;
                }
              },
              xAxis: {
                type: 'time',
                axisLabel: {
                  //  坐标轴显示最大最小值
                  show: true,
                  hideOverlap: true,
                  interval: '3',
                  formatter: '{HH}:{mm}',
                }
              },
              yAxis: {
                name: $(values).attr('DisplayName') + (unit != null && unit !== '' ? "(" + unit + ")" : ""),
                type: 'value'
              },
              series: echartsData
            });
          }
        });
      }
      break;
    case "8":// 状态节点
      cmd = gdv(eval('(' + obj.attr('cmd') + ')'), []);
      cmdValue = parseInt(gdv(dataValue, 0));
      for (var i = 0; i < cmd.length; i++) {
        let pmin = parseInt(cmd[i].min);
        let pmax = parseInt(cmd[i].max);
        if (cmdValue >= pmin && ((pmin == pmax && cmdValue == pmax) || cmdValue < pmax)) {
          obj.find("img").attr("src", cmd[i].src);
          break;
        }
      }
      break;
    case "9":// 开关
      cmdValue = parseInt(gdv(dataValue, 0));
      cmd = gdv(eval('(' + obj.attr('cmd') + ')'), []);
      for (var i = 0; i < cmd.length; i++) {
        let pmin = parseInt(cmd[i].min);
        let pmax = parseInt(cmd[i].max);
        if (cmdValue >= pmin && ((pmin == pmax && cmdValue == pmax) || cmdValue < pmax)) {
          obj.attr("val", cmdValue);
          obj.find("img").attr("src", cmd[i].src);
          break;
        }
      }
      break;
      /*		case "12"://滑动
                  let container = obj.find(".slider_container");
                  let handle = obj.find(".custom-slider-handle");
                  $('#'+obj.attr("id") +" .slider_container").slider({
                      range:"min",
                      min:0,
                      max: container.attr("max_length"),
                      value:dataValue,
                      create: function() {
                          handle.text( $( this ).slider( "value" ) );
                      },
                      slide: function( event, ui ) {
                          handle.text( ui.value );
                      },
                      stop: function( event, ui ) {
                          let params = {};
                          params[key] = ui.value;
                          sendAttribute(deviceId,params);
                      }
                  });
                  handle.text(dataValue);
                  let ranges = container.find(".ui-slider-range");
                  if(ranges.length > 1) {
                      ranges.each(function (index,item) {
                          if(index < ranges.length-1) {
                              item.remove();
                          }
                      })
                  }
              break;*/
      /*case "14":
              cmdValue = dataValue;
              if(!isNaN(Number(dataValue))) {  // 数字
                  cmdValue = parseInt(gdv(dataValue,0) );
              }
              cmd = gdv( eval('('+ obj.attr('cmd') +')') , [] );
              for( var i=0; i < cmd.length ; i++ ){
                  if(cmd[i].is_num != false) {
                      let pmin = parseInt(cmd[i].min);
                      let pmax = parseInt(cmd[i].max);
                      if( cmdValue >= pmin && ( (pmin == pmax && cmdValue == pmax   ) || cmdValue < pmax)){
                          obj.attr("jval" , cmdValue ) ;
                          obj.find("a").attr("href" , cmd[i].jurl );
                          break ;
                      }
                  } else {
                      if( cmdValue == cmd[i].val){
                          obj.attr("jval" , cmdValue ) ;
                          obj.find("a").attr("href" , cmd[i].jurl );
                          break ;
                      }
                  }

              }
      break;*/
    default:
      break;
  }


}

// eslint-disable-next-line no-unused-vars
function initSensorIdList(sensor_id_list, nidList) {
  for (let i = 0; i < nidList.length; i++) {
    let nid = nidList.eq(i);
    let sensor_id = nid.attr("sensor_id");
    if (sensor_id != undefined) {

      sensor_id_list[sensor_id] = ''
    }
  }
}

// eslint-disable-next-line no-unused-vars
function initWebsocketParam(sensor_id_list) {
  let param = '';
  for (let key in sensor_id_list) {
    param += key + ',';
  }
  return param
}

// eslint-disable-next-line no-unused-vars
function alarmWebsocket(model) {
  if ("WebSocket" in window) {
    let ws_protocal = "ws:";
    if (window.location.protocol == 'https:') {
      ws_protocal = "wss:";
    }
    let token = getToken()
    var p = '';
    if (model === '1') {
      p = encodeURI("dev=" + app.devCode)
    } else {
      p = encodeURI("farm=" + app.farmId);
    }
    app.alarmWs = new WebSocket(ws_protocal + iotbaseurlIP + "api/v1/alarmWebsocket?Authorization=" + token.split(" ")[1] + "&" + p);
    app.alarmWs.onopen = function () {
      /*that.ws.send();*/
      console.log("alarmWs链接成功")
    };
    app.alarmWs.onmessage = function (evt){
      let received_msg = evt.data;
      if (received_msg==='1'){
        return
      }
      let msg = JSON.parse(received_msg);
      let compareType='';
      switch (msg.CompareType){
        case 'above' : compareType='大于'
          break;
        case 'below' : compareType='小于'
          break;
        case 'equal' : compareType='等于'
          break;
        case 'notEqua' : compareType='不等于'
          break;
      }
      if (model){
        var deviceSensor = $("div[sensor_id="+msg.FieldName+"]");
        if (deviceSensor.length>0){
          app.$message.warning(msg.ConfigName+":"+msg.DisplayName+"的值"+msg.AlarmValue+compareType+msg.Value)
        }
      }else{
        var deviceSensor = $("div[sensor_id="+msg.FieldName+"][green_house_id="+msg.GreenHouseId+"][node_id="+msg.DevCode+"]");
        if (deviceSensor.length>0){
          app.$message.warning(msg.ConfigName+":"+msg.DisplayName+"的值"+msg.AlarmValue+compareType+msg.Value)
        }
      }
    }
    setInterval(function () {
      app.alarmWs.send("1")
    }, 10 * 1000);//跟websocket发送信息
  }
}
function initwebsocket(deviceId){
  let sensor_id_list = {}

  //nid 1 8 9
  let nid_1s = $("div[nid=1]");
  initSensorIdList(sensor_id_list, nid_1s)
  let nid_8s = $("div[nid=8]");
  initSensorIdList(sensor_id_list, nid_8s)
  let nid_9s = $("div[nid=9]");
  initSensorIdList(sensor_id_list, nid_9s)
  let nid_5s = $("div[nid=5]");
  initSensorIdList(sensor_id_list, nid_5s)

  let param = initWebsocketParam(sensor_id_list);
  let ws_protocal = "ws:";
  if (window.location.protocol == 'https:') {
    ws_protocal = "wss:";
  }
  let token = getToken()
  // 打开一个 web socket
  app.ws = new WebSocket(ws_protocal + iotbaseurlIP + "api/v1/websocket?Authorization=" + token.split(" ")[1] + "&devCode=" + deviceId + "&param=" + param);
  app.ws.onopen = function () {
    /*app.ws.send();*/
    console.log("webSocket链接成功")
  };
  app.ws.onmessage = function (evt) {
    let received_msg = evt.data;
    if (received_msg==='1'){
      return
    }
    let msg = JSON.parse(received_msg);
    for (const key in msg) {
      let msgElement = msg[key];
      let dateValue = msgElement.Value;
      let dateTime = '';
      let obj = $('div[sensor_id=' + msgElement.FieldName + ']');
      if (obj.length > 0) {
        for (let i = 0; i < obj.length; i++) {
          checkNid(obj[i], dateValue, msgElement.FieldName, deviceId, dateTime);
        }
      }
    }
  };
  app.ws.onerror= function (e){
    app.ws.close();
    console.error(e);
  }
  app.ws.onclose = function (e){
    console.info(e);
  }
}
function websocketBaseData(deviceId) {
  let that = this
  initControlNodeClick()//给开关添加点击事件
  initDeviceStatus();
  setInterval(function () {
    initDeviceStatus();
  }, 10 * 1000);//更新设备状态
  //initCameraPicture();
  /*setInterval( function() {
      initCameraPicture();
  }, 10* 1000 * 60 * 5);*/
  if ("WebSocket" in window) {
    initwebsocket(deviceId)
    if (app.wsTimer){
      clearInterval(app.wsTimer);
    }
    app.wsTimer=setInterval(function () {
      if (app.ws.readystate === app.ws.OPEN){
        app.ws.send("ping");
      }else{
        initwebsocket(deviceId)
      }
    }, 10 * 1000);
  } else {
    // 浏览器不支持 WebSocket
    layer.msg("您的浏览器不支持 WebSocket!", {icon: 2, time: 1500});
  }
  /*setInterval(function () {
    app.ws.send("1")
  }, 10 * 1000);//跟websocket发送信息*/
}

/**
 * 初始化实时数据
 */
function initBaseData() {
  let timeout=10*1000
  // sensor 动态数据
  initSensorData();

  setInterval(function () {
    initSensorData();
  }, timeout);

  // 控制节点
  initControlNode();
  initControlNodeClick();

  setInterval(function () {
    initControlNode();
  }, timeout);

  // 状态节点
  initStateNode();

  setInterval(function () {
    initStateNode();
  }, timeout);

  setInterval(function () {
    initDeviceStatus();
  }, timeout);


  udpChartValue();
  setInterval(function () {
    udpChartValue();
  }, timeout);

  /*initSlider()
   setInterval(function () {
       initSlider();
   }, 10 * 1000);*/
  /*initCameraPicture();
  setInterval(function () {
      initCameraPicture();
  }, 10 * 1000);*/
  /*initSwitchLink();
  setInterval(function () {
      initSwitchLink();
  }, 10 * 1000);*/
}

function conversionType(type, value){
  if (type==='int'){
     return  parseInt(value);
  }else if (type==='float'){
    return  parseFloat(value);
  }else if (type==='string'){
    return value.toString()
  }
}

/**
 * 绑定事件
 *
 */
function initControlNodeClick() {
  for (var k = 0; k < $("div[nid=9]").length; k++) {
    var deviceSensor = $("div[nid=9]").eq(k);
    var sensor_id = deviceSensor.attr("sensor_id");
    if (util.isNotEmpty(sensor_id)) {
      deviceSensor.click(async function () {
        let obj = $(this)
        var cmd = gdv(eval('(' + $(this).attr('cmd') + ')'), []);
        var cmdValue = parseInt(gdv($(this).attr('val'), 0));
        for (var i = 0; i < cmd.length; i++) {
          let pmin = parseInt(cmd[i].min);
          let pmax = parseInt(cmd[i].max);
          if (cmdValue >= pmin && ((pmin == pmax && cmdValue == pmax) || cmdValue < pmax)) {
            var node_id = obj.attr("node_id");
            var metaName = obj.attr("sensor_id");
            var metaName_father = obj.attr("sensor_id_father");
            var valueType = obj.attr("valueType");
            var childValueType = obj.attr("childValueType");
            let conversionType1=(cmd[i].send).toString()
            if (childValueType!=null){
              conversionType1 = conversionType(childValueType,(cmd[i].send));
            }
            try {
              layer.load(2)
              await commonAjax('POST', iotbaseurl + 'api/v1/dev/SetProperty', {
                DevCode: node_id,
                FieldName: metaName_father,
                Value: valueType==='struct'?JSON.stringify({metaName:conversionType1}):conversionType1,
                ValueType: valueType
              },async function (data) {
                if (data.Code == -1) {
                  app.$message.error(data.Message);
                } else {
                  let isTrue = ""
                  let ceshiNum = 0
                  let timer = await setInterval(async () => {
                    if(isTrue !=="" || ceshiNum==10){
                      layer.closeAll()
                      clearInterval(timer)
                      if (cmd[i].send==isTrue) {
                        for (var j = 0; j < cmd.length; j++) {
                          let min = parseInt(cmd[j].min);
                          let max = parseInt(cmd[j].max);
                          let send = parseInt(cmd[i].send);
                          if (send >= min && ((min == max && send == max) || send < max)) {
                            obj.find('img').attr("src", cmd[j].src)
                            obj.attr("val", send)
                          }
                        }
                        multivaluedSwitch(metaName, cmd[i].send)
                        //switchLinkUpdate(metaName,cmd[i].send)
                        var win_height = $(window).height();
                      } else if (isTrue !==cmd[i].send && isTrue !==cmdValue){
                      }else if (ceshiNum === 10){
                      }
                    }else{
                      isTrue = await contrastAttribute(node_id, metaName, (cmd[i].send).toString());
                    }
                    ceshiNum ++
                  },500)
                }
                app.inputData = '';
                app.dialogVisible = false;
              });
            } catch (error) {
              console.error(error);
            }


            /*						commonAjaxFalse("GET",baseurl+'api/deviceMeta/'+deviceId+'/meta/'+metaName,'',function (data){
                                        if (isModbus){
                                            method="modbusFunction";
                                            params.address=data.register+""
                                            params.name=data.name
                                            params.bit=data.bit==null?"null":data.bit
                                            params.dataType=data.dataType
                                            params.functionCode=data.functionCode+""
                                            params.outboundFormula=data.outboundFormula
                                            params.unitId=data.unitIdentifier
                                            params.value=parseInt(cmd[i].send)
                                        }else{
                                            method="thing.service.property.set";
                                            params[data.name] = parseFloat(cmd[i].send)
                                        }
                                        commonAjax('POST',baseurl+"api/plugins/rpc/twoway/"+deviceId, {
                                            method: method,
                                            params: params},
                                            function(data,status, xhr){
                                            app.lastTime = new Date().getTime() - 2*1000 ;
                                            if(xhr.status == 200){
                                                for (var j=0; j < cmd.length ; j++){
                                                    let min = parseInt(cmd[j].min);
                                                    let max = parseInt(cmd[j].max);
                                                    let send = parseInt(cmd[i].send);
                                                    if( send >= min && ( (min == max &&send == max ) || send<max)){
                                                        obj.find('img').attr("src",cmd[j].src)
                                                        obj.attr("val",send)
                                                    }
                                                }
                                                multivaluedSwitch(metaName,cmd[i].send)
                                                //switchLinkUpdate(metaName,cmd[i].send)
                                                var win_height = $(window).height() ;

                                                app.$message({
                                                    message: '成功',
                                                    type:'success',
                                                    offset:win_height/2.5,
                                                    center:true
                                                });
                                            }else{
                                                if (xhr.status == 408) {
                                                    app.$message.error('超时');
                                                } else if (xhr.status == 409) {
                                                    app.$message.error('设备不在线');
                                                } else {
                                                    app.$message.error('未知错误' + data.msg);
                                                }
                                            }
                                        });
                                    });*/
            break;
          }
        }
      })
    }
  }

  // 配置下发组件
  for (var i = 0; i < $("div[nid=1][cid=11]").length; i++) {
    var deviceSensor = $("div[nid=1][cid=11]").eq(i);
    var sensor_id = deviceSensor.attr("sensor_id");
    if (util.isNotEmpty(sensor_id)) {
      deviceSensor.click(function () {
        // --
        app.dialogVisible = true;
        var node_id = $(this).attr("node_id");
        let textTitle = $(this).attr("textTitle");
        app.downFieldName = $(this).attr("sensor_id");
        app.downFatherFieldName = $(this).attr("sensor_id_father");
        app.childValueType =  $(this).attr("childValueType");
        app.downValueType = $(this).attr("valuetype");
        app.downNowValue = $(this).attr("val");
        app.downDevCode = node_id;
        app.inputData = $(this).children("div").html()
        if (textTitle != null && textTitle !== '') {
          $(".el-dialog__title").html(textTitle);
        } else {
          $(".el-dialog__title").html("数据下发");
        }
      })
    }
  }


  for (var i = 0; i < $("div[nid=1][cid=7]").length; i++) {
    var deviceSensor = $("div[nid=1][cid=7]").eq(i);
    var sensor_id = deviceSensor.attr("sensor_id");
    if (util.isNotEmpty(sensor_id)) {
      deviceSensor.click(function () {
        // --
        app.dialogVisibleTime = true;
        var node_id = $(this).attr("node_id");
        let textTitle = $(this).attr("textTitle");
        app.downFieldName = $(this).attr("sensor_id");
        app.downFatherFieldName = $(this).attr("sensor_id_father");
        app.childValueType =  $(this).attr("childValueType");
        app.downValueType = $(this).attr("valuetype");
        app.downNowValue = $(this).attr("val");
        app.downDevCode = node_id;
        app.inputData = $(this).children("div").html()
        if (textTitle != null && textTitle !== '') {
          $(".el-dialog__title").html(textTitle);
        } else {
          $(".el-dialog__title").html("数据下发");
        }
      })
    }
  }
}

// 点击按钮后，循环查询设备属性值进行对比
function contrastAttribute(id, name, val) {
  return new Promise(function (resolve) {
    getAjax(iotbaseurl + 'api/v1/dev/value?devCode=' + id + '&fieldName=' + name, function (res) {
      if (res) {
        if (res.Code == 0 && res.Data.length > 0) {
          resolve(res.Data[0].Value);
        } else {
          resolve(false);
        }
      } else {
        resolve(false);
      }
    });
  });
}



function sendAttribute(deviceId, params) {
  commonAjax('POST', baseurl + "api/plugins/telemetry/DEVICE/" + deviceId + '/SHARED_SCOPE', params,
      function (data, status, xhr) {
        app.$message({message: '成功', type: 'success'});
        for (var key in params) {
          switchLinkUpdate(key, params[key]);
        }
      }, function (XMLHttpRequest, textStatus, errorThrown) {
        app.$message.error('错误:' + textStatus);
      });
}

/**
 * 控制
 * @returns
 */
function initControlNode() {
  for (var i = 0; i < $("div[nid=9]").length; i++) {
    let deviceSensor = $("div[nid=9]").eq(i);
    var sensor_id = deviceSensor.attr("sensor_id");
    var node_id = deviceSensor.attr("node_id");
    if (util.isNotEmpty(sensor_id)) {
      getAjax(iotbaseurl + 'api/v1/dev/value?devCode=' + node_id + '&fieldName=' + sensor_id, function (res) {
        if (res) {
          var objs = $("div[nid=9][sensor_id=" + res.name + "]");
          for (var k = 0; k < objs.length; k++) {
            var obj = objs.eq(k);
            var cmdValue = parseInt(gdv(res.Data[0].Value, 0));
            var cmd = gdv(eval('(' + obj.attr('cmd') + ')'), []);
            for (var i = 0; i < cmd.length; i++) {
              let pmin = parseInt(cmd[i].min);
              let pmax = parseInt(cmd[i].max);
              if (cmdValue >= pmin && ((pmin == pmax && cmdValue == pmax) || cmdValue < pmax)) {
                obj.attr("val", cmdValue);
                obj.find("img").attr("src", cmd[i].src);
                break;
              }
            }
          }
        }
      });
    }
  }
}

/**
 * 状态初始化
 */
function initStateNode() {
  for (var i = 0; i < $("div[nid=8]").length; i++) {
    var sensor_id = $("div[nid=8]").eq(i).attr("sensor_id");
    var node_id = $("div[nid=8]").eq(i).attr("node_id");
    if (util.isNotEmpty(sensor_id)) {
      getAjax(iotbaseurl + 'api/v1/dev/value?devCode=' + node_id + '&fieldName=' + sensor_id, function (res) {
        if (res) {
          var objs = $("div[nid=8][sensor_id=" +sensor_id + "]");
          for (var k = 0; k < objs.length; k++) {
            var obj = objs.eq(k);
            var cmd = gdv(eval('(' + obj.attr('cmd') + ')'), []);
            var cmdValue = parseInt(gdv(res.Data[0].Value, 0));
            for (var i = 0; i < cmd.length; i++) {
              if (cmdValue >= cmd[i].min && ((cmd[i].min == cmd[i].max && cmdValue == cmd[i].max) || cmdValue < cmd[i].max)) {
                obj.find("img").attr("src", cmd[i].src);
                break;
              }
            }
          }
        }
      });
    }
  }
}

/**
 * 滑块数据初始化
 */
function initSlider() {
  // nid = 12 滑块
  let silderElem = $("div[nid=12]");
  for (let i = 0; i < silderElem.length; i++) {
    let sensor_id = silderElem.eq(i).attr("sensor_id");
    let isModbus = silderElem.eq(i).attr("isModbus");
    let device_slave_id = silderElem.eq(i).attr("device_slave_id");
    let node_id = silderElem.eq(i).attr("node_id");
    let deviceId = getDeviceId(node_id, device_slave_id, isModbus);
    if (util.isNotEmpty(sensor_id)) {
      getAjax(baseurl + 'api/deviceMeta/' + deviceId + '/meta/' + sensor_id, function (res) {
        if (res) {
          var cl = $("div[nid=12][sensor_id=" + res.name + "]");
          var container = cl.find(".slider_container");
          var handle = cl.find(".custom-slider-handle");
          $('#' + cl.attr("id") + " .slider_container").slider({
            range: "min",
            min: 0,
            max: container.attr("max_length"),
            value: res.value,
            create: function () {
              handle.text($(this).slider("value"));
            },
            slide: function (event, ui) {
              handle.text(ui.value);
            },
            stop: function (event, ui) {
              var params = {};
              params[sensor_id] = ui.value;
              sendAttribute(deviceId, params);
            }
          });
          handle.text(res.value);
          var ranges = container.find(".ui-slider-range");
          if (ranges.length > 1) {
            ranges.each(function (index, item) {
              if (index < ranges.length - 1) {
                item.remove();
              }
            })
          }
        }
      });
    }
  }
}

/**
 * 拍照预览数据初始化
 */
function initCameraPicture() {
  // nid = 13 拍照预览
  let silderElem = $("div[nid=13]");
  for (let i = 0; i < silderElem.length; i++) {
    let node_id = silderElem.eq(i).attr("node_id");
    if (util.isNotEmpty(node_id)) {
      getAjax(baseurl + 'api/camera/picture/latestById?deviceId=' + node_id, function (res) {
        if (res) {
          var cl = silderElem.eq(i);
          var container = cl.find(".camera_picture_container");
          var image = container.find("img");
          image.attr('src', res.imageSrc);
        }
      });
    }
  }
}

/**
 * 条件跳转初始化
 */
function initSwitchLink() {
  // nid = 14 条件跳转
  let silderElem = $("div[nid=14]");
  for (let i = 0; i < silderElem.length; i++) {
    let sensor_id = silderElem.eq(i).attr("sensor_id");
    let isModbus = silderElem.eq(i).attr("isModbus");
    let device_slave_id = silderElem.eq(i).attr("device_slave_id");
    let node_id = silderElem.eq(i).attr("node_id");
    let deviceId = getDeviceId(node_id, device_slave_id, isModbus);
    if (util.isNotEmpty(sensor_id)) {
      getAjax(baseurl + 'api/deviceMeta/' + deviceId + '/meta/' + sensor_id, function (res) {
        if (res) {
          var objs = $("div[nid=14][sensor_id=" + res.name + "]");
          for (var k = 0; k < objs.length; k++) {
            var obj = objs.eq(k);
            var cmdValue = res.value;
            if (!isNaN(Number(cmdValue))) {  // 数字
              cmdValue = parseInt(gdv(res.value, 0));
            }
            var cmd = gdv(eval('(' + obj.attr('cmd') + ')'), []);
            for (var i = 0; i < cmd.length; i++) {
              if (cmd[i].is_num != false) {
                let pmin = parseInt(cmd[i].min);
                let pmax = parseInt(cmd[i].max);
                if (cmdValue >= pmin && ((pmin == pmax && cmdValue == pmax) || cmdValue < pmax)) {
                  obj.attr("jval", cmdValue);
                  obj.find("a").attr("href", cmd[i].jurl);
                  break;
                }
              } else {
                if (cmdValue == cmd[i].val) {
                  obj.attr("jval", cmdValue);
                  obj.find("a").attr("href", cmd[i].jurl);
                  break;
                }
              }

            }
          }
        }
      });
    }
  }
}

/**
 * 数据初始化
 */
function initSensorData() {
  // nid = 1 传感器动态数据
  for (var i = 0; i < $("div[nid=1]").length; i++) {
    var sensor_id = $("div[nid=1]").eq(i).attr("sensor_id");
    var node_id = $("div[nid=1]").eq(i).attr("node_id");
    if (util.isNotEmpty(sensor_id)) {
      getAjax(iotbaseurl + 'api/v1/dev/value?devCode=' + node_id + '&fieldName=' + sensor_id, function (res) {
        if (res) {
          let cid = $("div[nid=1][sensor_id=" + res.name + "]").eq(0).attr("cid");
          let obj = $("div[nid=1][sensor_id=" + res.name + "]");
          let dataValue=res.Data[0].Value
          let value;
          if (cid === "7") {
            value = (dataValue != null && dataValue !== '' ? dataValue : '00:00')
            if (value.length < 4) {
              value = value.padStart(4, '0');
              value = value.toString().slice(0, 2) + ':' + value.toString().slice(2);
            }
            obj.find(".canvas_text").html(value)
          } else if (cid === "11" || cid === "12") {
            value = (dataValue != null && dataValue !== '' ? dataValue : 0.00)
            obj.find(".canvas_text").html(value)
          }
        }
      });
    }
  }
}
function playHls(url,video){
  let hls = new Hls();
  hls.loadSource(url);
  hls.attachMedia(video);
  hls.on(Hls.Events.MANIFEST_PARSED,function() {
    video.play();
  });
  hls.on(Hls.Events.ERROR,function (status,msg){
    // 监听出错事件
    console.log("加载失败");
  });
}
function playFlv(url,video){
  if (flvjs.isSupported()) {
    var flvPlayer = flvjs.createPlayer({
      type: 'flv',
      url: url
    });
    flvPlayer.attachMediaElement(video);
    flvPlayer.load(); //加载
  }
}
/**
 * 视频初始化
 * @returns
 */
function initVideo(model, devCode) {
  $(".videoNode").each(function () {
    let node_id = $(this).attr("node_id");
    let video_id = $(this).attr("video_id");
    let video_way = $(this).attr("video_way");
    let video_type = $(this).attr("video_type");
    let video_url = $(this).attr("video_url");
    let jq = $(this).find("video").attr('id');
    let video = document.getElementById(jq);
    if (devCode != null && devCode !== '') {
      if (model === '0') {
        devCode = node_id;
      }else{
        devCode = video_id;
      }
      if (video_way=='1'){
          if (video_type=='1'){
            playFlv(video_url,video)
          }else{
            playHls(video_url,video)
          }
      }else{
        commonAjax('GET', iotbaseurl + 'api/v1/dev/getByCode/'+devCode, '', function (e) {
            if (e.Data.Flv != null && e.Data.Flv != '') {
              let url=e.Data.Flv
              if (video_type=='1'){
                playFlv(url,video)
              }else{
                playHls(url,video)
              }
            }
        });
      }
    }
  })
}
/**
 * 第一次进入的时候重新初始化chart对象
 * 取标签中的option属性重新初始化
 * @returns
 */
function reinitChartObj() {
  var chartMap = app.chartMap;
  $(".chartStyle").each(function () {
    var id = $(this).parent().attr("id");
    var cid = $(this).parent().attr("cid");
    if (cid == 4) {
      var json = $(this).attr("option");
      var myChart = echarts.init($(this)[0]);
      var option = JSON.parse(json);
      option.series[0].data = [{name: 'sensor', value: 0}];
      myChart.setOption(option);
      app.chartMap[id] = myChart;
    } else if (cid == 10) {
      var json = $(this).attr("option");
      var myChart = echarts.init($(this)[0]);
      var option = JSON.parse(json);
      option.series[0].effect.show = false;
      myChart.setOption(option);
      app.chartMap[id] = myChart;
    } else if (id != null) {
      var json = $(this).attr("option");
      var myChart = echarts.init($(this)[0]);
      let parse = JSON.parse(json);
      parse.series[0].data = [0];
      if (parse.xAxis != null)
        parse.xAxis.data = [];
      myChart.setOption(parse, true);
      app.chartMap[id] = myChart;

    }
  })
  // 初始化列表
  refleshSensorList();
}

function reinitDiv(t_select_deviceId) {
  $('div[nid]').each(function () {
    $(this).attr("node_id", t_select_deviceId)
  })
}

/**
 * 列表数据初始化
 */
function refleshSensorList() {
  $(".chartStyle").each(function () {
    var id = $(this).parent().attr("id");
    var sensor_id = $(this).parent().attr("sensor_id");
    var node_id = $(this).parent().attr("node_id");
    var cid = $(this).parent().attr("cid");
    var max = $(this).parent().attr("max");
    var unit = $(this).parent().attr("unit");
    var that = this;
    if (id != null) {
      if (sensor_id != null) {
        if (cid == 3) {
          // 仪表盘
          commonAjax("GET", iotbaseurl + 'api/v1/dev/value?devCode=' + node_id + '&fieldName=' + sensor_id, '', function (res) {
            if (res.Data.length > 0) {
              let data = res.Data[0];
              $(that).parent().attr("DisplayName", data.DisplayName)
              app.chartMap[id].setOption({
                series: [{
                  data: [{value: data.Value, name: data.DisplayName}]
                }]
              });
            }
          });
        } else if (cid == 4) {
          // 液位图
          commonAjax("GET", iotbaseurl + 'api/v1/dev/value?devCode=' + node_id + '&fieldName=' + sensor_id, '', function (res) {
            if (res.Data.length > 0) {
              let data = res.Data[0];
              app.chartMap[id].setOption({
                series: [{
                  data: [{
                    name: 'sensor',
                    value: (data.Value != null && data.Value !== '' ? parseInt(data.Value) : 0) / max
                  }]
                }]
              });
            }
          });
        }/* else if (cid == 10) {
					// 管道图
					getAjax(baseurl+'api/deviceMeta/'+deviceId+'/meta/'+sensor_id, function (res) {
						if (res) {
							var json = $(that).attr("option");
							var option = JSON.parse(json);
							option.series[0].effect.show = res.value > 0;
							app.chartMap[id].setOption(option);
						}
					});
				} */ else {
          commonAjaxFalse('GET', iotbaseurl + 'api/v1/dev/value?devCode=' + node_id + '&fieldName=' + sensor_id, '', function (res) {
            if (res.Data.length > 0) {
              let data = res.Data[0];
              $(that).parent().attr("DisplayName", data.DisplayName)
            }
            //$(that).parent().attr("DisplayName", data.aliasName)
          })
        }
      }
    }
  })
}

/**
 * 图表数据更新
 */
function udpChartValue() {
  $(".chartStyle").each(function () {
    var id = $(this).parent().attr("id");
    var sensor_id = $(this).parent().attr("sensor_id");
    var cid = $(this).parent().attr("cid");
    var max = $(this).parent().attr("max");
    var DisplayName = $(this).parent().attr("DisplayName");
    var node_id = $(this).parent().attr("node_id");
    var unit = $(this).parent().attr("unit");
    var that = this;
    if (id != null && sensor_id != null) {
      getAjax(iotbaseurl + 'api/v1/dev/value?devCode=' + node_id + '&fieldName=' + sensor_id, function (res) {
        if (res) {
          if (cid == 3) {
            // 表盘类型
            if (res.Data.length > 0) {
              let data = res.Data[0];
              app.chartMap[id].setOption({
                series: [{
                  data: [{value: data.Value, name: data.DisplayName}]
                }]
              });
            }
          } else if (cid == 4) {
            // 液位图
            if (res.Data.length > 0) {
              let data = res.Data[0];
              app.chartMap[id].setOption({
                series: [{
                  data: [{
                    name: 'sensor',
                    value: (data.Value != null && data.Value !== '' ? parseInt(data.Value) : 0) / max
                  }]
                }]
              });
            }

          }else {
            commonAjax("POST", iotbaseurl + 'api/v1/curve/list', {
              'DevCode': node_id,
              'FieldName': sensor_id
            }, function (res) {
              if (res.Data.length > 0) {
                var x_data = [];
                var y_data = [];
                let echartsData = [];
                if (res) {
                  var datat = res.Data;
                  if (datat != null) {
                    let sortS = [];
                    for (let w in datat) {
                      let elem = [datat[w].DataTime, datat[w].Value];
                      sortS.push(elem);
                    }
                    echartsData.push({
                      name: sensor_id,
                      connectNulls: false,
                      data: sortS
                    });
                  }
                }
                app.chartMap[id].x_data = x_data;
                app.chartMap[id].y_data = y_data;
                app.chartMap[id].setOption({
                  grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '4%',
                    containLabel: true
                  },
                  dataZoom: [
                    {
                      show: true,
                      start: 90,
                      end: 100
                    },
                    {
                      type: 'inside',
                      start: 0,
                      end: 100,
                      handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                      handleSize: '80%',
                      handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                      }
                    }
                  ],
                  tooltip: {
                    trigger: 'axis',
                    formatter: function (params) {
                      let result = '';
                      params.forEach(function (item) {
                        let date = new Date(item.value[0])
                        result += date.format("MM-dd hh:mm:ss") + "</br>" + item.marker + " " + item.seriesName + ":" + item.value[1] + "</br>";
                        //result+=formattedDate+ "</br>" + item.marker + " " + item.seriesName + ":" + item.value[1] + "</br>";
                      });
                      return result;
                    }
                  },
                  xAxis: {
                    type: 'time',
                    axisLabel: {
                      //  坐标轴显示最大最小值
                      show: true,
                      hideOverlap: true,
                      interval: '3',
                      formatter: '{HH}:{mm}',
                    }
                  },
                  yAxis: {
                    name: DisplayName + (unit != null && unit !== '' ? "(" + unit + ")" : ""),
                    type: 'value'
                  },
                  series: echartsData
                });
              }
            });
          }
        }
      });
    }
  })
}

function scaled() {
  app.changescaler = app.changescaler + 0.1;
  var xr = app.changescaler;
  var win_width = $(window).width();
  var win_height = $(window).height();

  var xwidth = 0;
  var xheight = 0;

  if (xr < 1 && app.scaler != 1) {
    xwidth = (win_width - app.orginWidth * xr) / 2 / xr;
    xheight = (win_height - app.orginHeight * xr) / 2 / xr;
  }

  xwidth = xwidth > 0 ? xwidth : 0;
  xheight = xheight > 0 ? xheight : 0;

  $(".edit-container").css({
    "-webkit-transform": "scale(" + xr + ", " + xr + " ) translate(" + xwidth + "px," + xheight + "px)",
    "transform": "scale(" + xr + ", " + xr + " ) translate(" + xwidth + "px," + xheight + "px)"
  });
}

function scalex() {
  if (app.changescaler < 0.39) {
    return;
  }
  app.changescaler = app.changescaler - 0.1;
  var xr = app.changescaler;

  var win_width = $(window).width();
  var win_height = $(window).height();

  var xwidth = 0;
  var xheight = 0;

  if (xr < 1 && app.scaler != 1) {
    xwidth = (win_width - app.orginWidth * xr) / 2 / xr;
    xheight = (win_height - app.orginHeight * xr) / 2 / xr;
  }

  xwidth = xwidth > 0 ? xwidth : 0;
  xheight = xheight > 0 ? xheight : 0;
  $(".edit-container").css({
    "-webkit-transform": "scale(" + xr + ", " + xr + " ) translate(" + xwidth + "px," + xheight + "px)",
    "transform": "scale(" + xr + ", " + xr + " ) translate(" + xwidth + "px," + xheight + "px)"
  });
}

function scalen() {
  var xr = app.scaler;

  xwidth = 0;
  xheight = 0;
  app.scaler = 1
  app.changescaler = 1
  $(".edit-container").css({
    "-webkit-transform": "scale(" + xr + ", " + xr + " ) translate(" + xwidth + "px," + xheight + "px)",
    "transform": "scale(" + xr + ", " + xr + " ) translate(" + xwidth + "px," + xheight + "px)"
  });
}

//
//----------基础方法-----------------------------------------------------------------------------
//
function tip(content, time, func) {
  if (content == undefined) {
    content = "error";
  }
  try {
    if (time == null || time == '')
      time = 1200;
    if (func == null)
      layer.msg(content, {time: time});
    else {
      layer.msg(content, {time: time}, function () {
        func();
      });
    }
  } catch (e) {
  }
};

function getToken() {
  //检查是否登录
  let token = localStorage.getItem('TOKEN')
  if(!token) {
    top.location.replace('login.html');
  }
  return 'Bearer ' + token
  // let cookieStr = document.cookie
  // var arrcookie = cookieStr.split(";");
  // for (var i = 0; i < arrcookie.length; i++) {
  //     var arr = arrcookie[i].split("=");
  //     if (arr[0] === 'Authorization') {
  //         let s = arr[1].replace("%20", " ");
  //         if (s != null && typeof s !== undefined && s !== '') {
  //             return s
  //         } else {
  //             top.location.replace('login.html');
  //         }
  //     } else {
  //         top.location.replace('login.html');
  //     }
  // }
}

function getVisualDisplayToken() {
  let storage = localStorage.getItem("layuiAdminVisualDisplay");
  if (storage == null) {
    return null;
  }
  let storageJson = JSON.parse(storage);
  let token = storageJson.token;
  let tokenLastTime = storageJson.tokenLastTime;
  let period = Date.now() - tokenLastTime;
  if (token != null && period < 60 * 60 * 1000) {
    return JSON.parse(token)
  } else {
    return null
  }
}

var isOk = isOK;

function getAjax(url, sucessCallBack, errorCallBack) {
  if (typeof (ucode) == "undefined") {
    ucode = '';
  }
  let token = getToken();
  $.ajax({
    type: "GET",
    url: url,
    contentType: "application/json",
    dataType: "json",
    async: true,
    headers: {
      'Authorization': token
    },
    success: function (data) {
      sucessCallBack(data);
    },
    error: errorCallBack
  })
};

function isOK(e) {
  if (e.status == 2) {
    return true;
  } else {
    return false;
  }
}

function isNotEmpty(val) {
  if (val != null && val != '') {
    return true;
  } else {
    return false;
  }
}

function commonAjaxFalse(method, url, data, sucessCallBack, errorCallBack) {
  var config = {
    type: method,
    url: url,
    async: false,
    contentType: "application/json",
    dataType: "json",
    success: function (data, status, xhr) {
      if (xhr.status == 401) {
        layer.msg('登录过期', {icon: 2, time: 3000}, function () {
          top.location.replace('login.html');
        }, 1000);
        return;
      }
      sucessCallBack(data, status, xhr);
    },
    error: errorCallBack
  };
  let token = getToken();
  if (token) {
    config.headers = {'Authorization': token};
  }
  if (method.toUpperCase() != 'GET' && method.toUpperCase() != 'DELETE') {
    config.data = JSON.stringify(data);
  }
  $.ajax(config)
}

function commonAjax(method, url, data, sucessCallBack, errorCallBack) {
  var config = {
    type: method,
    url: url,
    contentType: "application/json",
    dataType: "json",
    async: true,
    success: function (data) {
      if (data.status == 20000) {
        return;
      } else {
        sucessCallBack(data);
      }
    },
    error: errorCallBack
  };
  let token = getToken();
  if (token) {
    config.headers = {'Authorization': token};
  }
  if (method.toUpperCase() != 'GET' && method.toUpperCase() != 'DELETE') {
    config.data = JSON.stringify(data);
  }
  $.ajax(config)
};


function  fromCode (str) {
  //定义密钥，36个字母和数字
  var key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var st = key.length;  //获取密钥的长度
  var b, b1, b2, b3, d = 0, s;  //定义临时变量
  s = new Array(Math.floor(str.length / 3));  //计算加密字符串包含的字符数，并定义数组
  b = s.length;  //获取数组的长度
  for (var i = 0; i < b; i ++) {  //以数组的长度循环次数，遍历加密字符串
    b1 = key.indexOf(str.charAt(d));  //截取周期内第一个字符串，计算在密钥中的下标值
    d ++;
    b2 = key.indexOf(str.charAt(d));  //截取周期内第二个字符串，计算在密钥中的下标值
    d ++;
    b3 = key.indexOf(str.charAt(d));  //截取周期内第三个字符串，计算在密钥中的下标值
    d ++;
    s[i] = b1 * st * st + b2 * st + b3  //利用下标值，反推被加密字符的Unicode编码值
  }
  b = eval("String.fromCharCode(" + s.join(',') + ")");//用fromCharCode()算出字符串
  return b ;  //返回被解密的字符串
}

function refreshToken(){
  commonAjax("GET", iotbaseurl + 'api/v1/refreshToken', '', function (res) {
    localStorage.setItem("TOKEN",res.token)
  })
}
